package cn.sun.org.controller;

import cn.sun.basic.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.sun.basic.util.PageBean;
import cn.sun.org.domain.Department;
import cn.sun.org.query.DepartmentQuery;
import cn.sun.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门接口
 *    crud
 *    分页+高级
 */
@RestController //@Controller+@ResponseBody
@RequestMapping("/department")
@Api(value = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    //添加或修改-差异在于是否有id put
    @PutMapping
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加！")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        //通过id判断是添加或者修改
        try {
            if (department.getId()!=null){
                departmentService.update(department);
            }else {
                departmentService.save(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存失败！"+e.getMessage());
        }

    }

    //删除   delete
    //写一个接口必须思考三个方面
    // 1 访问地址
    // 2 传递什么参数
    // 3 返回什么值 yes no JsonResult(yes/no msg)
    // 其实对于增删改，我们只关心是否成功，已经失败了的信息
    // 方案1： 字符串{success:true,message:"操作失败“}
    // 方案2： 写一个对象返回+@ResponseBody----》{success:true,message:"操作失败“}
    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable("id") Long id){

        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败!"+e.getMessage());
        }
    }

    //获取一个 get
    @GetMapping("/{id}") //Get http://localhost:8080/deparment/1 deparment/2
    public Department findById(@PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    //获取所有 get
    @GetMapping ///department
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    //分页+高级查询 //post /department 传递对象都往@RequestBody
    @PostMapping
    public PageBean<Department> findPage(@RequestBody DepartmentQuery query){
        return departmentService.findPage(query);
    }

    @PatchMapping
    public AjaxResult drukdel(@RequestBody List<Long> ids){
        try {
            departmentService.drukdel(ids);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败");
        }
    }
    @GetMapping("/deptTree")
    public List<Department> getDeptTree(){
           return departmentService.getDeptTree();
    }
}
